﻿using Microsoft.Extensions.DependencyInjection;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Yitter.IdGenerator;

namespace Wen.Core.Extensions;

public static class FreeSqlServiceExtension
{
    public static IServiceCollection AddFreeSqlServices(this IServiceCollection services,
        Func<IServiceProvider, (FreeSql.DataType dbtype, string conString)> conn,
        Action<IFreeSql>? changed = null)
    {
        // 初始化配置
        var options = new IdGeneratorOptions(workerId: 1); // WorkerId范围0~63
        YitIdHelper.SetIdGenerator(options);
        services.AddSingleton(r =>
        {
            var (dbType, connString) = conn(r);

            IFreeSql fsql = new FreeSql.FreeSqlBuilder()
                .UseConnectionString(dbType, connString)
                .UseAdoConnectionPool(true)
#if DEBUG
                .UseMonitorCommand(cmd => Console.WriteLine($"Sql：{cmd.CommandText}"))
                .UseAutoSyncStructure(true) //自动同步实体结构到数据库，只有CRUD时才会生成表
#endif
                .CreateDatabaseIfNotExistsSqlServer()
                .Build();

            fsql.Aop.AuditValue += (s, e) =>
            {
                if (e.Column.CsType == typeof(long) &&
                    e.Property.GetCustomAttribute<KeyAttribute>(false) != null &&
                    e.Value?.ToString() == "0")
                    e.Value = YitIdHelper.NextId();
            };

            fsql.Aop.ConfigEntityProperty += (s, e) =>
            {
                if (e.Property.GetCustomAttribute<KeyAttribute>() is not null)
                    e.ModifyResult.IsPrimary = true; //Key
            };

            changed?.Invoke(fsql);
            return fsql;
        });
        return services;
    }
}
